$(document).ready(function($){
    $('[data-inf-bind]').each(function(index, element){
        $('[name="' + $(element).attr('data-inf-bind') + '"]')
            .on('change', inf_action).trigger('change');
    });
});

function inf_action(e){
    var sender = $(e.target);

    if(sender.val() !== undefined && sender.val().length) {
        var targets = $('[data-inf-bind="' + sender.attr('name') + '"]');

    targets.each(function(idx, target){
        var data = new FormData();

        data.append('informilo', $(target).attr('data-informilo'));
        data.append('filtro', sender.val());
        data.append('csrfmiddlewaretoken', getCookie('csrftoken'));

        $.ajax({
            url: informiloj_url,
            type: 'POST',
            async: true,
            data: data,
            cache: false,
            dataType: 'json',
            processData: false,
            contentType: false
            })
            .done(function (result) {
                if(result.status === 'ok') {
                    var inf_content = '';
                    var val_before = $(target).val();
                    $(target).text('');

                    $.each(result.informilo, function(idx, cur){
                        $('<option value="' + cur.uuid + '"' + (cur.uuid === val_before ? 'selected=""': '')
                            + '>' + cur.nomo + '</option>').appendTo(target);
                    });
                } else {
                    console.log("Bad server response: " + result.err);
                }
            })
            .fail(function (jqXHR, textStatus) {
                console.log("Request failed: " + textStatus);
            });
        });
    }
}
